package defectsim;

import defectsim.DefectFactory.DefectType;

public class DislocationSource extends DefectAgent{

	private double direction;
	private double nucleationStress;
	private double nucleationTime;
	private double elapsedTime;
	private boolean nucleation;
	private double nucleationLength;

	SimEnvironment env = SimEnvironment.getInstance();

	public double getDirection() {
		return direction;
	}

	public void setDirection(double direction) {
		this.direction = direction;
	}

	@Override
	public void percept() {
		Material mat = env.getCurrentMaterial();
		nucleationStress = mat.getNucleationStress();
		nucleationTime = mat.getNucleationTime();
		nucleationLength = 1e-3 * mat.getShearModulus() * mat.getBurgersVector() /
		(2 * Math.PI * nucleationStress * (1 - mat.getPoissonRatio() * mat.getPoissonRatio()));
	}

	@Override
	public void mentalUpdate() {
		if (Math.abs(env.getCurrentExternalStress()) > nucleationStress){
			nucleation = true;
		}
		else
			nucleation = false;

	}

	@Override
	public void act() {
		if (true){ 
			elapsedTime += env.getTimeStep();
//			if (elapsedTime >= nucleationTime){
			if (Math.IEEEremainder(env.getCurrentTick(), env.getCyclicTickCount() / 2) == 0.0){
				double dx = nucleationLength * Math.cos(direction * Math.PI / 180);
				double dy = nucleationLength * Math.sin(direction * Math.PI / 180);
				EdgeDislocation d1 = (EdgeDislocation)DefectFactory.createDefect(DefectType.EdgeDislocation);
				d1.setDirection(direction);
				d1.setUnitBurgersVector(1.0);
				d1.setX(this.getX() - dx);
				d1.setY(this.getY() - dy);
//				d1.setDipole(true);
				EdgeDislocation d2 = (EdgeDislocation)DefectFactory.createDefect(DefectType.EdgeDislocation);
				d2.setDirection(direction);
				d2.setUnitBurgersVector(-1.0);
				d2.setX(this.getX() + dx);
				d2.setY(this.getY() + dy);
//				d2.setDipole(true);
//				d1.setDipoleMate(d2);
//				d2.setDipoleMate(d1);
				env.nucleate(d1);
				env.nucleate(d2);
				elapsedTime = 0;
			}
		}
	}

	public DislocationSource(){
		nucleation = false;
		elapsedTime = 0;
	}

}
